from datetime import datetime

from django.utils import timezone

from rest_framework import serializers

from ..models import *


# 库存表
class FaKuyouGoodsStockSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouGoodsStock
        fields = '__all__'


# 仓库表
class FaKuyouStoresSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouStores
        fields = '__all__'


# 调拨单
class FaKuyouAllocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouAllocation
        fields = '__all__'


# 调拨详情单
class FaKuyouAllocationInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouAllocationInfo
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 验证调拨数量
        if data.get('number') is not None and data['number'] <= 0:
            raise serializers.ValidationError({
                'number': '调拨数量必须大于0'
            })

        # 验证调入调出仓库
        if data.get('stores_out') and data.get('stores_enter'):
            if data['stores_out'] == data['stores_enter']:
                raise serializers.ValidationError({
                    'stores_enter': '调入仓库不能与调出仓库相同'
                })

        return data


# 成本调整单
class FaKuyouAdjustmentSerializer(serializers.ModelSerializer):
    business_type_display = serializers.CharField(
        source='get_business_type_display',
        read_only=True,
        help_text='业务类型'
    )
    purchase_datetime = serializers.SerializerMethodField(
        help_text='单据日期'
    )
    create_datetime = serializers.SerializerMethodField(
        help_text='创建时间'
    )
    update_datetime = serializers.SerializerMethodField(
        help_text='更新时间'
    )

    class Meta:
        model = FaKuyouAdjustment
        fields = '__all__'
        extra_kwargs = {
            'money': {'coerce_to_string': False},
        }

    def validate(self, data):
        """单据日期不能晚于当前时间"""
        if data.get('purchase_time') and data['purchase_time'] > int(time.time()):
            raise serializers.ValidationError({
                'purchase_time': '单据日期不能晚于当前时间'
            })
        return data


# 成本调整单详情
class FaKuyouAdjustmentInfoSerializer(serializers.ModelSerializer):
    purchase_datetime = serializers.SerializerMethodField(
        help_text='单据日期'
    )
    create_datetime = serializers.SerializerMethodField(
        help_text='创建时间'
    )
    update_datetime = serializers.SerializerMethodField(
        help_text='更新时间'
    )

    class Meta:
        model = FaKuyouAdjustmentInfo
        fields = '__all__'
        extra_kwargs = {
            'money': {'coerce_to_string': False},
        }

    def validate(self, data):
        """单据日期不能晚于当前时间"""
        if data.get('purchase_time') and data['purchase_time'] > int(time.time()):
            raise serializers.ValidationError({
                'purchase_time': '单据日期不能晚于当前时间'
            })
        return data


# 盘点
class FaKuyouInventorySerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouInventory
        fields = '__all__'

    def validate(self, data):
        """盘点时间不能晚于当前时间"""
        if data.get('purchase_time') and data['purchase_time'] > int(time.time()):
            raise serializers.ValidationError({
                'purchase_time': '盘点时间不能晚于当前时间'
            })
        return data


# 盘点详情
class FaKuyouInventoryInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouInventoryInfo
        fields = '__all__'

    def validate(self, data):
        """盘点时间不能晚于当前时间"""
        if data.get('purchase_time') and data['purchase_time'] > int(time.time()):
            raise serializers.ValidationError({
                'purchase_time': '盘点时间不能晚于当前时间'
            })

        # 验证库存不能为负数
        if data.get('stock') is not None and data['stock'] < 0:
            raise serializers.ValidationError({
                'stock': '系统库存不能为负数'
            })

        if data.get('invertory_stock') is not None and data['invertory_stock'] < 0:
            raise serializers.ValidationError({
                'invertory_stock': '盘点库存不能为负数'
            })

        return data


# 序列号盘点
class FaKuyouInventorySerialSerializer(serializers.ModelSerializer):
    store_type_display = serializers.CharField(
        source='get_store_type_display',
        read_only=True,
        help_text='盘点范围'
    )
    purchase_datetime = serializers.SerializerMethodField(
        help_text='盘点时间'
    )
    create_datetime = serializers.SerializerMethodField(
        help_text='创建时间'
    )
    update_datetime = serializers.SerializerMethodField(
        help_text='更新时间'
    )

    class Meta:
        model = FaKuyouInventorySerial
        fields = '__all__'

    def validate(self, data):
        """盘点时间不能晚于当前时间"""
        if data.get('purchase_time') and data['purchase_time'] > int(time.time()):
            raise serializers.ValidationError({
                'purchase_time': '盘点时间不能晚于当前时间'
            })
        return data


# 序列号盘点详情
class FaKuyouInventorySerialInfoSerializer(serializers.ModelSerializer):
    serial_list = serializers.SerializerMethodField(
        help_text='序列号列表'
    )
    serial_count = serializers.SerializerMethodField(
        help_text='序列号总数'
    )
    purchase_datetime = serializers.SerializerMethodField(
        help_text='盘点时间'
    )
    create_datetime = serializers.SerializerMethodField(
        help_text='创建时间'
    )
    update_datetime = serializers.SerializerMethodField(
        help_text='更新时间'
    )

    class Meta:
        model = FaKuyouInventorySerialInfo
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 验证库存不能为负数
        if data.get('stock') is not None and data['stock'] < 0:
            raise serializers.ValidationError({
                'stock': '系统库存不能为负数'
            })

        if data.get('invertory_stock') is not None and data['invertory_stock'] < 0:
            raise serializers.ValidationError({
                'invertory_stock': '盘点库存不能为负数'
            })

        # 验证序列号数量与库存关系
        if data.get('period_period') and data.get('stock'):
            serial_count = len(data['period_period'].split(','))
            if serial_count > data['stock']:
                raise serializers.ValidationError({
                    'period_period': '序列号数量不能超过系统库存'
                })

        return data


# 其他入库单
class FaKuyouWarehousingSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouWarehousing
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 审核时必须指定审核人
        if data.get('examine_status') == '1' and not data.get('examine_id'):
            raise serializers.ValidationError({
                'examine_id': '审核时必须指定审核人'
            })

        # 单据时间不能晚于当前时间
        if data.get('purchase_time') and data['purchase_time'] > int(time.time()):
            raise serializers.ValidationError({
                'purchase_time': '单据时间不能晚于当前时间'
            })

        # 数量必须大于0
        if data.get('number') is not None and data['number'] <= 0:
            raise serializers.ValidationError({
                'number': '入库数量必须大于0'
            })

        # 金额不能为负数
        if data.get('price') is not None and data['price'] < 0:
            raise serializers.ValidationError({
                'price': '入库金额不能为负数'
            })

        return data


# 其他入库单详情
class FaKuyouWarehousingInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouWarehousingInfo
        fields = '__all__'

    def validate(self, data):
        """数据验证"""
        # 验证数量必须大于0
        if data.get('number') is not None and data['number'] <= 0:
            raise serializers.ValidationError({
                'number': '入库数量必须大于0'
            })

        # 验证单价不能为负数
        if data.get('unit_price') is not None and data['unit_price'] < 0:
            raise serializers.ValidationError({
                'unit_price': '入库单价不能为负数'
            })

        # 验证库存不能为负数
        if data.get('stock') is not None and data['stock'] < 0:
            raise serializers.ValidationError({
                'stock': '可用库存不能为负数'
            })

        # 验证生产日期和保质期的逻辑
        if data.get('manufacture') and data.get('guarantee'):
            if data['manufacture'] > int(time.time()):
                raise serializers.ValidationError({
                    'manufacture': '生产日期不能晚于当前时间'
                })
            if data['guarantee'] <= 0:
                raise serializers.ValidationError({
                    'guarantee': '保质期必须大于0'
                })

        return data


# 其他出库单
class FaKuyouWarehouseSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouWarehouse
        fields = '__all__'

    def validate(self, data):
        """Business logic validation"""
        if data.get('examine_status') == '1' and not data.get('examine_time'):
            data['examine_time'] = int(datetime.now().timestamp())
        return data


# 其他出库详情单
class FaKuyouWarehouseInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouWarehouseInfo
        fields = '__all__'

    def validate(self, data):
        """Validate business logic"""
        # Validate expiration dates
        if data.get('manufacture') and data.get('guarantee'):
            calculated_validity = data['manufacture'] + (data['guarantee'] * 86400)
            if data.get('validity') and data['validity'] != calculated_validity:
                raise serializers.ValidationError({
                    'validity': '有效期与生产日期+保质期计算结果不匹配'
                })

        # Validate quantity and price
        if data.get('number') is not None and data.get('number') <= 0:
            raise serializers.ValidationError({
                'number': '出库数量必须大于0'
            })

        return data

    def to_representation(self, instance):
        """Add additional calculated fields"""
        ret = super().to_representation(instance)
        ret['total_value'] = float(instance.price) if instance.price else 0.0
        return ret


# 组装单
class FaKuyouAssembleSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouAssemble
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
        }

    def validate(self, data):
        """Business logic validation"""
        # Auto set examine_time when status changes to approved
        if data.get('examine_status') == '1' and not data.get('examine_time'):
            data['examine_time'] = int(datetime.now().timestamp())

        # Validate money is positive if provided
        if data.get('money') is not None and data['money'] < 0:
            raise serializers.ValidationError({
                'money': '费用金额不能为负数'
            })

        return data

    def to_representation(self, instance):
        """Add additional calculated fields"""
        ret = super().to_representation(instance)
        ret['is_approved'] = instance.examine_status == '1'
        return ret


# 组装详情单
class FaKuyouAssembleInfoSerializer(serializers.ModelSerializer):
    # 显示字段
    business_type_display = serializers.CharField(
        source='get_business_type_display',
        read_only=True
    )
    type_display = serializers.CharField(
        source='get_type_display',
        read_only=True
    )
    examine_status_display = serializers.CharField(
        source='get_examine_status_display',
        read_only=True
    )

    # 计算字段
    total_cost = serializers.SerializerMethodField()
    validity_date = serializers.SerializerMethodField()

    class Meta:
        model = FaKuyouAssembleInfo
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
            'purchase_code': {'required': True},
            'goods_id': {'required': True},
        }

    def get_total_cost(self, obj):
        """计算总成本"""
        return obj.total_cost

    def get_validity_date(self, obj):
        """格式化过期时间"""
        if obj.validity:
            return timezone.datetime.fromtimestamp(obj.validity).strftime('%Y-%m-%d')
        return None

    def validate(self, data):
        """业务逻辑验证"""
        # 验证组合件和子件的数量关系
        if data.get('type') == '1' and float(data.get('number', 0)) <= 0:
            raise serializers.ValidationError("组合件数量必须大于0")

        # 验证库存是否充足
        if float(data.get('allow_stock', 0)) < float(data.get('number', 0)):
            raise serializers.ValidationError("库存数量不足")

        return data

    def to_representation(self, instance):
        """增强API返回数据"""
        ret = super().to_representation(instance)
        # 添加关联商品信息（实际项目中需要从其他模型获取）
        ret['goods_name'] = "关联商品名称"
        ret['stores_name'] = "仓库名称"
        return ret


# 组装模板
class FaKuyouAssembleTempSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouAssembleTemp
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
        }

    def validate(self, data):
        """Business logic validation"""
        # Auto set examine_time when status changes to approved
        if data.get('examine_status') == '1' and not data.get('examine_time'):
            data['examine_time'] = int(datetime.now().timestamp())

        # Validate template name is unique for admin
        if 'temp_name' in data and self.instance:
            if FaKuyouAssembleTemp.objects.filter(
                    admin_id=data.get('admin_id', self.instance.admin_id),
                    temp_name=data['temp_name']
            ).exclude(pk=self.instance.pk).exists():
                raise serializers.ValidationError({
                    'temp_name': '该模板名称已存在'
                })

        # Validate money is positive if provided
        if data.get('money') is not None and data['money'] < 0:
            raise serializers.ValidationError({
                'money': '费用金额不能为负数'
            })

        return data

    def to_representation(self, instance):
        """Add additional calculated fields"""
        ret = super().to_representation(instance)
        ret['is_approved'] = instance.examine_status == '1'
        ret['is_template'] = True  # Mark as template for frontend
        return ret


# 组装模板详情
class FaKuyouAssembleInfoTempSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouAssembleInfoTemp
        fields = '__all__'

    def validate(self, data):
        """Validate business logic"""
        # Validate quantity is positive
        if data.get('number') is not None and data.get('number') <= 0:
            raise serializers.ValidationError({
                'number': '数量必须大于0'
            })

        # Auto set examine_time when status changes to approved
        if data.get('examine_status') == '1' and not data.get('examine_time'):
            data['examine_time'] = int(datetime.now().timestamp())

        return data

    def to_representation(self, instance):
        """Add additional calculated fields"""
        ret = super().to_representation(instance)
        ret['is_approved'] = instance.examine_status == '1'
        ret['is_component'] = instance.type == '1'
        ret['is_template'] = True  # Mark as template for frontend
        return ret


# 拆卸单
class FaKuyouSplitSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouSplit
        fields = '__all__'
    def validate(self, data):
        """业务逻辑验证"""
        # 自动生成单据编号
        if not data.get('purchase_code'):
            from datetime import datetime
            date_prefix = datetime.now().strftime('%Y%m%d')
            last_record = FaKuyouSplit.objects.filter(
                purchase_code__startswith=f'DS{date_prefix}'
            ).order_by('-id').first()

            if last_record:
                last_num = int(last_record.purchase_code[-4:])
                new_num = f"{last_num + 1:04d}"
            else:
                new_num = "0001"

            data['purchase_code'] = f"DS{date_prefix}{new_num}"

        # 费用不能为负数
        if data.get('money') and float(data['money']) < 0:
            raise serializers.ValidationError("费用金额不能为负数")

        return data

    def to_representation(self, instance):
        """增强API返回数据"""
        ret = super().to_representation(instance)
        # 添加关联信息
        ret['preparation_name'] = "制单人姓名"  # 实际应从用户表获取
        ret['operation_name'] = "操作人姓名"
        ret['examine_name'] = "审核人姓名"
        return ret


# 拆卸详情单
class FaKuyouSplitInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouSplitInfo
        fields = '__all__'
    def validate(self, data):
        """业务逻辑验证"""
        # 库存校验
        if float(data.get('number', 0)) > float(data.get('allow_stock', 0)):
            raise serializers.ValidationError({
                'number': '数量不能超过可用库存'
            })

        # 组合件校验
        if data.get('type') == '1' and float(data.get('number', 0)) <= 0:
            raise serializers.ValidationError({
                'number': '组合件数量必须大于0'
            })

        return data

    def to_representation(self, instance):
        """增强API返回数据"""
        ret = super().to_representation(instance)
        # 添加关联信息
        ret['goods_name'] = "商品名称"  # 应从商品表获取
        ret['stores_name'] = "仓库名称"
        ret['unit_name'] = "单位名称"
        ret['status_badge'] = instance.status_badge
        return ret


# 拆卸模板
class FaKuyouSplitTempSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouSplitTemp
        fields = '__all__'


    def validate(self, data):
        """模板特有验证逻辑"""
        # 模板名称必填
        if not data.get('temp_name'):
            raise serializers.ValidationError({
                'temp_name': '模板名称不能为空'
            })

        # 费用不能为负数
        if 'money' in data and data['money'] and float(data['money']) < 0:
            raise serializers.ValidationError({
                'money': '费用金额不能为负数'
            })

        return data

    def to_representation(self, instance):
        """增强API返回数据"""
        ret = super().to_representation(instance)
        # 添加关联信息
        ret['preparation_name'] = "制单人"  # 实际应从用户表获取
        ret['operation_name'] = "操作人"
        ret['status'] = 'draft'  # 标记为草稿状态
        return ret


# 拆卸模板详情
class FaKuyouSplitInfoTempSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouSplitInfoTemp
        fields = '__all__'

    def validate(self, data):
        """模板特有验证逻辑"""
        # 模板允许负库存
        if 'number' in data and float(data['number']) <= 0:
            raise serializers.ValidationError({
                'number': '数量必须大于0'
            })

        # 商品必须存在
        if 'goods_id' in data and data['goods_id'] == 0:
            raise serializers.ValidationError({
                'goods_id': '必须选择商品'
            })

        return data

    def to_representation(self, instance):
        """增强API返回数据"""
        ret = super().to_representation(instance)
        # 添加关联信息（实际应从其他服务获取）
        ret['goods_name'] = "商品名称"
        ret['stores_name'] = "仓库名称"
        ret['unit_name'] = "单位名称"
        ret['status'] = 'draft'  # 标记为草稿状态
        return ret
